<?php
class UserModel extends Model
{
	# Installation
	public static function install()
	{
		return array
		(
			'admin'		=>	'TINYINT(1) DEFAULT 0',
			'username'	=>	'VARCHAR(12) UNIQUE',
			'password'	=>	'CHAR(32)',
			'date'		=>	'TIMESTAMP DEFAULT CURRENT_TIMESTAMP',
			'email'		=>	'VARCHAR(255) UNIQUE',
			'status'	=>	'TINYINT(1) DEFAULT 0',
			'confirm'	=>	'CHAR(32)'
		);
	}
	
	# Authentication
	private static $auth = null;
	
	public static function authenticate($user)
	{
		self::$auth = $user;
		
		fw::set_cookie('user', $user->password.$user->id);
	}
	
	public static function unauthenticate()
	{
		self::$auth = false;
		
		fw::delete_cookie('user');
	}
	
	public static function is_authenticated()
	{
		if(is_null(self::$auth))
		{
			self::$auth = false;
			
			$cookie = fw::get_cookie('user');
			
			if($cookie)
			{
				$id = substr($cookie, 32);
				
				if(is_numeric($id))
				{
					self::$auth = new User($id);
					
					if(!self::$auth->assoc || self::$auth->password != substr($cookie, 0, 32))
					{
						self::$auth = false;
					}
				}
			}
		}
		
		return self::$auth?self::$auth->id:0;
	}
	
	# Log in
	public static function log_in()
	{
		$form = new Form('log_in');
		
		$form->field('username', 'text', array
		(
			'exists'	=>	array('UserModel', 'username_exists')
		));
		
		$form->field('password', 'password', array
		(
			'wrong'		=>	array('UserModel', 'check_password')
		));
		
		if($data = $form->validate())
		{
			$row = db::fetch(db::query('SELECT `id` FROM `'.DB_PREFIX.'User` WHERE `username`="'.db::escape($data['username']).'"'), 'row');
			
			self::authenticate(new User($row[0]));
			
			return null;
		}
		
		return $form;
	}
	
	public static function username_exists($username)
	{
		return db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `username`="'.db::escape($username).'" AND `status`!=0'));
	}
	
	public static function check_password($password, $request)
	{
		return db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `username`="'.db::escape($request['username']).'" AND `password`="'.md5($password).'"'))?true:false;
	}
	
	# Register
	public static function register()
	{
		$form = new Form('register');
		
		$form->field('username', 'text', array
		(
			'min_length'	=>	3,
			'max_length'	=>	12,
			'alphanumeric'	=>	lang('alphanumeric'),
			'unique'		=>	array('UserModel', 'unique_username')
		));
		
		$form->field('email', 'text', array
		(
			'max_length'	=>	255,
			'valid_email'	=>	true,
			'unique'		=>	array('UserModel', 'unique_email')
		));
		
		$form->field('password', 'password', array
		(
			'confirm'		=>	true,
			'min_length'	=>	6
		));
		
		if($data = $form->validate())
		{
			$confirm = md5(uniqid());
			
			new User(array
			(
				'username'	=>	$data['username'],
				'password'	=>	md5($data['password']),
				'email'		=>	$data['email'],
				'confirm'	=>	$confirm
			));
			
			$registration = array
			(
				'title'		=>	fw::config('title'),
				'username'	=>	$data['username'],
				'password'	=>	$data['password'],
				'confirm'	=>	'http://'.$_SERVER['HTTP_HOST'].WEB.'confirm/'.$confirm.'/',
				'delete'	=>	'http://'.$_SERVER['HTTP_HOST'].WEB.'delete/'.$confirm.'/'
			);
			
			mail($data['email'], lang('account_details'), lang('email_register', $registration), 'From: noreply@'.$_SERVER['HTTP_HOST']);
		}
		
		return $form;
	}
	
	public static function unique_username($username)
	{
		return !db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `username`="'.db::escape($username).'"'));
	}
	
	public static function unique_email($email, $request, $id)
	{
		if($id == 'profile' && $email == self::$auth->email) return true;
		
		return !db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE `email`="'.db::escape($email).'"'));
	}
	
	# Forgot password
	public static function forgot()
	{
		$form = new Form('forgot');
		
		$form->field('username_or_email', 'text', array
		(
			'exists'		=>	array('UserModel', 'username_or_email')
		));
		
		if($data = $form->validate())
		{
			$user = db::fetch(db::query('SELECT `id`, `username`, `email` FROM `'.DB_PREFIX.'User` WHERE (`username`="'.db::escape($data['username_or_email']).'" OR `email`="'.db::escape($data['username_or_email']).'") AND `status`!=0'));
			
			$confirm = md5(uniqid());
			
			$forgot = array
			(
				'title'		=>	fw::config('title'),
				'username'	=>	$user['username'],
				'password'	=>	substr($confirm, -8),
				'confirm'	=>	'http://'.$_SERVER['HTTP_HOST'].WEB.'forgot/'.$confirm.'/'
			);
			
			db::query('UPDATE `'.DB_PREFIX.'User` SET `status`=2, `confirm`="'.$confirm.'" WHERE `id`='.$user['id']);
			
			mail($user['email'], lang('account_details'), lang('email_forgot', $forgot), 'From: noreply@'.$_SERVER['HTTP_HOST']);
		}
		
		return $form;
	}
	
	public static function username_or_email($value)
	{
		return db::num_rows(db::query('SELECT NULL FROM `'.DB_PREFIX.'User` WHERE (`username`="'.db::escape($value).'" OR `email`="'.db::escape($value).'") AND `status`!=0'))?true:false;
	}
	
	# Profile
	public static function profile()
	{
		$form = new Form('profile');
		
		$form->field('email', 'text', array
		(
			'max_length'	=>	255,
			'valid_email'	=>	true,
			'unique'		=>	array('UserModel', 'unique_email')
		), self::$auth->email);
		
		$form->field('password', 'password', array
		(
			'optional'		=>	true,
			'confirm'		=>	true,
			'min_length'	=>	6
		));
		
		if($data = $form->validate())
		{
			self::$auth->email = $data['email'];
			
			if($data['password'] != '') self::$auth->password = md5($data['password']);
		}
		
		return $form;
	}
	
	# Static user
	public static function is_admin()
	{
		return self::$auth->admin?true:false;
	}
	
	public static function username()
	{
		return self::$auth->username;
	}
}